import time
from common.functions import open_browser
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, WebDriverException, InvalidElementStateException



class Base:
    """
    封装selenium的基础方法，给page包里的类继承
    """

    def __init__(self, driver):
        self.driver = driver

    def get(self, url):
        # 请求网址
        try:
            self.driver.get(url)
        except (WebDriverException, InvalidElementStateException):
            print('请输入正确的网址')

    def find_element(self, locator, timeout=5):
        """
        定位元素
        :param locator: 元组(By.XX,'xx')
        :param timeout: 超时时间
        :return: 元素element
        """
        try:
            element = WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located(locator))
            return element
        except TimeoutException:
            print('元素定位失败')

    def click(self, locator):
        # 元素点击操作
        element = self.find_element(locator)
        if element:
            element.click()

    def get_attribute(self, locator, attr):
        # 获取元素属性操作
        element = self.find_element(locator)
        if element:
            return element.get_attribute(attr)   # 返回正确的属性，没有返回None

    def send_keys(self, locator, content):
        # 元素输入操作
        element = self.find_element(locator)
        if element:
            element.send_keys(content)

    def get_element_text(self,locator):
        # 获取标签文本
        element = self.find_element(locator)
        if element:
            return  element.text

    def implicit_waiting(self, seconds=10):
        # 隐式等待时间设置
        self.driver.implicitly(seconds)

    def forward(self):
        # 游览器前进操作
        self.driver.forward()

    def back(self):
        # 游览器后退操作
        self.driver.back()

    def refresh(self):
        # 游览器刷新操作
        self.driver.refresh()

    def quit(self, seconds=0):
        # 退出游览器
        time.sleep(seconds)
        self.driver.quit()


if __name__ == '__main__':
    driver = open_browser()  # 调用common的open_browser()函数
    base = Base(driver)
    base.get('https://www.baidu.com')
    base.find_element((By.ID,'kw'),timeout=3)
    base.quit(2)
